'use strict';

const Controller = require('egg').Controller;
const Res = require('../utils/response');
const joi = require("joi")

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class CookBookController extends Controller {
  // 获取数据
  async show() {
    const {
      ctx
    } = this;
    const query = {
      limit: toInt(ctx.query.limit),
      offset: toInt(ctx.query.offset)
    };
    if (ctx.query.is) {
      Object.assign(query, {
        where: {
          state: 2
        }
      })
    }
    const result = await ctx.model.CookBook.findAll(query);
    for (let i = 0; i < result.length; i++) {
      let item = result[i];
      const userinfo = await ctx.model.Users.findAll({
        where: {
          id: item.user_id
        }
      });
      result[i].dataValues.userinfo = userinfo;
      const category = await ctx.model.Category.findAll({
        where: {
          id: item.category_id
        }
      });
      result[i].dataValues.category = category;
    }
    ctx.body = Res(0, result);
  }

  // 搜索数据
  async search() {
    const schema = {
      name: joi.number(),
      id: joi.number()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    const result = await this.ctx.model.CookBook.findAll({
      where: {
        name: {
          $like: `%${value&&value.name || ''}%`
        },
        id: {
          $like: `%${value&&value.id || ''}%`
        }
      }
    })
    this.ctx.body = Res(0, result);
  }

  // 点赞
  async setFavoriteCount() {
    const ctx = this.ctx;
    const schema = {
      user_id: joi.number().required(),
      favorite_type: joi.number().required(),
      id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }

    const item = await ctx.model.CookBook.findByPk(value.id);
    if (!item) {
      ctx.status = 404;
      return;
    }

    await item.update({
      favorite_count: item.favorite_count + 1
    });
    await ctx.model.Favorite.findOrCreate({
      where: {
        cook_id: value.id
      },
      defaults: {
        cook_id: value.id,
        favorite_type: value.favorite_type,
        user_id: value.user_id
      }
    })
    ctx.body = Res(0, item);
  }

  // 根据分类id获取食谱
  async findByCategoryId() {
    const {
      ctx
    } = this;
    const schema = {
      category_id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.query, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    const result = await ctx.model.CookBook.findAll({
      where: {
        state: 2,
        cook_type: 2,
        category_id: value.category_id
      },
      order: [
        ['sort', 'desc']
      ]
    })
    if (!result) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '数据不存在');
    }
    for (let i = 0; i < result.length; i++) {
      let item = result[i];
      const userinfo = await ctx.model.Users.findAll({
        where: {
          id: item.user_id
        }
      });
      result[i].dataValues.userinfo = userinfo;
      const category = await ctx.model.Category.findAll({
        where: {
          id: item.category_id
        }
      });
      result[i].dataValues.category = category;
    }
    ctx.body = Res(0, result);
  }

  // 食谱详情
  async findById() {
    const ctx = this.ctx;
    const schema = {
      id: joi.number().required()
    }
    console.log('ctx.request.body', ctx.request.body)
    const {
      error,
      value
    } = joi.validate(ctx.request.query, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    const result = await ctx.model.CookBook.findOne({
      where: {
        id: value.id
      }
    })
    if (!result) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '数据不存在');
    }
    const _step = await ctx.model.Step.findAll({
      where: {
        cook_id: value.id
      }
    })
    const _material = await ctx.model.Material.findAll({
      where: {
        cook_id: value.id
      }
    })
    const userinfo = await ctx.model.Users.findAll({
      where: {
        id: result.user_id
      }
    });

    const category = await ctx.model.Category.findAll({
      where: {
        id: result.category_id
      }
    });

    result.dataValues.category = category;
    result.dataValues.userinfo = userinfo;
    result.dataValues.step = _step;
    result.dataValues.material = _material;
    ctx.body = Res(0, result);
  }

  // 通过cookid查找步骤
  async findStepById() {
    const ctx = this.ctx;
    const schema = {
      id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    const result = await ctx.model.Step.findAll({
      where: {
        id: value.id
      }
    })
    if (!result) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '数据不存在');
    }
    ctx.body = Res(0, result);
  }


  // 通过cookid查材料
  async findMaterailById() {
    const ctx = this.ctx;
    const schema = {
      id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    const result = await ctx.model.Material.findAll({
      where: {
        id: value.id
      }
    })
    if (!result) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '数据不存在');
    }
    ctx.body = Res(0, result);
  }

  // 添加数据
  async create() {
    const ctx = this.ctx;
    const schema = {
      name: joi.string().required(),
      desc: joi.string().required(),
      cover: joi.string().required(),
      steps: joi.array().required(),
      materials: joi.array().required(),
      category_id: joi.number().required(),
      user_id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    console.log('校验之后的值：', value);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    console.log('解析的结果为：', value.materials);
    // const _steps = JSON.parse(value.steps);
    const result = await ctx.model.CookBook.create({
      name: value.name,
      desc: value.desc,
      cover: value.cover,
      category_id: value.category_id,
      user_id: value.user_id
    });
    if (!result) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    value.materials.forEach(async e => {
      await ctx.model.Material.create({
        name: e.name,
        number: e.num,
        cook_id: result.id
      })
    })
    value.steps.forEach(async e => {
      await ctx.model.Step.create({
        desc: e.name,
        cover: e.url,
        cook_id: result.id
      })
    })
    ctx.status = 200;
    ctx.body = Res(200, null, '插入成功');
  }

  // 1：未通过审核  2：通过审核
  async changeType() {
    const ctx = this.ctx;
    const schema = {
      cook_type: joi.number().required(),
      id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }

    const item = await ctx.model.CookBook.findByPk(value.id);
    if (!item) {
      ctx.status = 404;
      return;
    }

    await item.update(value);
    ctx.body = Res(0, item);
  }

  // // 1：上架  2：下架
  async changeState() {
    const ctx = this.ctx;
    const schema = {
      state: joi.number().required(),
      id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }

    const item = await ctx.model.CookBook.findByPk(value.id);
    if (!item) {
      ctx.status = 404;
      return;
    }

    await item.update(value);
    ctx.body = Res(0, item);
  }

  // 食谱总数
  async count() {
    const {
      ctx
    } = this;
    const result = await ctx.model.CookBook.findAndCountAll({
      where: {
        state: 2,
      }
    });
    ctx.body = Res(0, result);
  }

  // 修改新秀的排序
  async newShow() {
    const {
      ctx
    } = this;
    const schema = {
      sort: joi.number().required(),
      id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.query, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }

    const item = await ctx.model.CookBook.findByPk(value.id);
    if (!item) {
      ctx.status = 404;
      return;
    }
    await item.update(value);
    ctx.body = Res(0, item);
  }

  // 修改新秀的排序
  async addStep() {
    const {
      ctx
    } = this;
    const schema = {
      desc: joi.string().required(),
      cover: joi.string().required(),
      cook_id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    const item = await ctx.model.Step.create({
      desc: value.desc,
      cover: value.cover,
      cook_id: value.cook_id
    });
    if (!item) {
      ctx.status = 404;
      return;
    }
    ctx.body = Res(0, item);
  }

  // 修改新秀的排序
  async addMaterial() {
    const {
      ctx
    } = this;
    const schema = {
      name: joi.string().required(),
      number: joi.string().required(),
      cook_id: joi.number().required()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    const item = await ctx.model.Material.create({
      name: value.name,
      number: value.number,
      cook_id: value.cook_id
    });
    if (!item) {
      ctx.status = 404;
      return;
    }
    ctx.body = Res(0, item);
  }
}

module.exports = CookBookController;